package org.adw.launcher2.ld.secret.ui;

import java.util.ArrayList;
import java.util.List;
import org.adw.launcher2.R;
import org.adw.launcher2.ld.secret.db.DatabaseHelper;
import org.adw.launcher2.ld.secret.db.MySMSCache;
import org.adw.launcher2.ld.secret.dom.contact.ConversationSMS;
import org.adw.launcher2.ld.secret.ui.adapter.ConversationSMSAdapter;
import org.adw.launcher2.ld.secret.ui.utils.Global;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ViewConversationSMSActivity extends Activity{// view one conversation between us and
	// 1 other user
    private static final int MAX_SMS_MESSAGE_LENGTH = 160;
	private static final String SMS_DELIVERED = "SMS_DELIVERED";
	private static final String SMS_SENT = "SMS_SENT";
	public ListView listView;
	public ConversationSMSAdapter adapter;
	public Button btnSend;
	public int userId;
	public EditText txtMessageInfo;
	public String phoneNumber = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_conversation_sms);
		Global.dbHelper = DatabaseHelper.getInstance(this);
		userId = getIntent().getExtras().getInt("ID");
		listView = (ListView) findViewById(R.id.listSMSConversation);
		btnSend = (Button) findViewById(R.id.btnSendConversation);
		txtMessageInfo = (EditText) findViewById(R.id.messageConversation);
        registerReceiver(sendreceiver, new IntentFilter(SMS_SENT));
        registerReceiver(deliveredreceiver, new IntentFilter(SMS_DELIVERED));
		loadConversation();
		btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				sendSms(phoneNumber, txtMessageInfo.getText().toString());
			}
		});
	}
	private void loadConversation() {
		AsyncTask<Uri, Void, List<ConversationSMS>> task = new AsyncTask<Uri, Void, List<ConversationSMS>>(){

			@Override
			protected List<ConversationSMS> doInBackground(Uri... params) {
				MySMSCache.getInstance(Global.dbHelper).loadConversationSMS(userId);
				return null;
			}
			@Override
			protected void onPostExecute(List<ConversationSMS> result) {
				if(result.get(0)!=null){
					phoneNumber = result.get(0).phoneNumber;
				}
				bindView(result);
			}
			
		};
		task.execute();
	}
	protected void bindView(List<ConversationSMS> result) {
		adapter = new ConversationSMSAdapter(this, R.layout.view_conversation_sms_item,
				result);
		listView.setAdapter(adapter);
	}
	private void sendSms(String phonenumber,String message){
    	SmsManager manager = SmsManager.getDefault();
    	PendingIntent piSend = PendingIntent.getBroadcast(this, 0, new Intent(SMS_SENT), 0);
    	PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0, new Intent(SMS_DELIVERED), 0);
    		int length = message.length();
    		if(length > MAX_SMS_MESSAGE_LENGTH){
    			ArrayList<String> messagelist = manager.divideMessage(message);
    			
    			manager.sendMultipartTextMessage(phonenumber, null, messagelist, null, null);
    		}else{
    			manager.sendTextMessage(phonenumber, null, message, piSend, piDelivered);
    		}
    	}
	
	private BroadcastReceiver sendreceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String info = "Send information: ";
			switch(getResultCode()){
				case Activity.RESULT_OK: info += "send successful"; break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE: info += "send failed, generic failure"; break;
				case SmsManager.RESULT_ERROR_NO_SERVICE: info += "send failed, no service"; break;
				case SmsManager.RESULT_ERROR_NULL_PDU: info += "send failed, null pdu"; break;
				case SmsManager.RESULT_ERROR_RADIO_OFF: info += "send failed, radio is off"; break;
			}
			Toast.makeText(getBaseContext(), info, Toast.LENGTH_SHORT).show();
		}
	};
	
	private BroadcastReceiver deliveredreceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent){
			String info = "Delivery information: ";
			switch(getResultCode()){
				case Activity.RESULT_OK: 
					insertIntoSMSData();
					info += "delivered"; 
					break;
				case Activity.RESULT_CANCELED: 
					info += "not delivered";
					break;
			}
			Toast.makeText(getBaseContext(), info, Toast.LENGTH_SHORT).show();
		}
	};

	protected void insertIntoSMSData() {// back up sent message by me
		Global.dbHelper = DatabaseHelper.getInstance(this);
		MySMSCache cache = MySMSCache.getInstance(Global.dbHelper);
		String message = txtMessageInfo.getText().toString();
		ContentValues values = new ContentValues();
		values.put("id", userId);
		values.put("is_me", 1);
		values.put("value", message);
		cache.insertSMSToDb(values);
		
	}
	@Override
		protected void onDestroy() {
    	unregisterReceiver(sendreceiver);
    	unregisterReceiver(deliveredreceiver);
		super.onDestroy();
		}
}
